#!/bin/bash

# 彩色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

BASE_PATH=$(cd "$(dirname "$0")"; pwd)
Log="$BASE_PATH/run.log"
PID_FILE="$BASE_PATH/app.pid"

function get_pid() {
  if [ -f "$PID_FILE" ]; then
    pid=$(cat "$PID_FILE")
    if [ -n "$pid" ] && kill -0 "$pid" > /dev/null 2>&1; then
      echo "$pid"
    else
      echo -e "${YELLOW}检测到无效 PID，清理 $PID_FILE${NC}"
      rm -f "$PID_FILE"
      echo ""
    fi
  fi
}

function start() {
  # 判断是否传入 JAR 文件名
  if [ -n "$2" ]; then
    TargetJar="$BASE_PATH/$2"
  else
    TargetJar=$(find "$BASE_PATH" -maxdepth 1 -type f -name "*.jar" | head -n 1)
  fi

  if [ ! -f "$TargetJar" ]; then
    echo -e "${RED}未找到JAR包: $TargetJar${NC}"
    exit 1
  fi

  BASENAME=$(basename "$TargetJar" .jar)
  Log="$BASE_PATH/$BASENAME.log"
  PID_FILE="$BASE_PATH/$BASENAME.pid"

  pid=$(get_pid)
  if [ -n "$pid" ]; then
    echo -e "${RED}应用正在运行，PID=$pid${NC}"
    exit 1
  fi

  echo -e "${GREEN}正在启动应用...${NC}"
  nohup java -Xms512m -Xmx512m -jar "$TargetJar" > "$Log" 2>&1 &
  echo $! > "$PID_FILE"
  sleep 3
  echo -e "${GREEN}应用已启动，PID=$(cat "$PID_FILE")${NC}"
  tail -n 100 "$Log"
}

function stop() {
  pid=$(get_pid)
  if [ -z "$pid" ]; then
    echo -e "${YELLOW}应用已停止${NC}"
    return
  fi

  echo -e "${YELLOW}正在停止应用 -> PID=$pid${NC}"
  kill -15 "$pid"
  sleep 2
  if kill -0 "$pid" > /dev/null 2>&1; then
    echo -e "${RED}应用未完全停止，尝试强制杀死...${NC}"
    kill -9 "$pid"
    sleep 1
    if kill -0 "$pid" > /dev/null 2>&1; then
      echo -e "${RED}强制杀死失败，请手动处理 PID=$pid${NC}"
      exit 1
    fi
  fi
  rm -f "$PID_FILE"
  echo -e "${GREEN}应用已停止${NC}"
}

function status() {
  pid=$(get_pid)
  if [ -n "$pid" ]; then
    echo -e "${GREEN}应用正在运行，PID=$pid${NC}"
  else
    echo -e "${YELLOW}应用已停止${NC}"
  fi
}

function log() {
  lines=${2:-10}
  if ! [[ "$lines" =~ ^[0-9]+$ ]]; then
    echo -e "${RED}参数错误：请传入数字作为日志行数${NC}"
    exit 1
  fi
  echo -e "${YELLOW}显示日志文件 $Log 的最后 $lines 行，并持续监听...${NC}"
  tail -n "$lines" -f "$Log"
}

# 命令分发
case "$1" in
  start) start "$@" ;;
  stop) stop ;;
  restart) stop && start "$@" ;;
  status) status ;;
  log) log "$@" ;;
  *)
    echo "用法: $0 {start|stop|restart|status|log} [参数]"
    echo "示例:"
    echo "  $0 start your-app.jar     # 启动指定 JAR"
    echo "  $0 log 50                 # 查看日志最后 50 行"
    exit 1
    ;;
esac
